WejustcreatedourNodeunit'sfirstunittest.However,ittests
mathfunctioninaratherisolatedway.Isupposeyouarewondering
howwecanuseNodeunittotestfunctionswithcomplexarguments
suchasHTTPrequestandresponse,thatareboundtoacontext.
Thisispossibleusingso-calledmockobjects.Theyarea
predefinedversionofthestateofcomplexcontext-basedarguments
orfunctions,inobjectsthatwewanttouseinourunittestinorder
totestthebehaviorofourmodulefortheexactstateoftheobject.
Tousemockobjects,wewillneedtoinstallamodulethatsupports
objectmocking.Therearevarioustypesoftestingtoolsand
modulesavailableoutthere.Mostofthem,however,aredesigned
totesttheJavaScriptclientfunctionality.Therearemodulessuch
asJsMockito,aJavaScriptforkofthefamousMockitoframework
forJava,andnode-inspector,amodulethatprovidesaJavaScript
debuggerthatstartsimplicitlyintheGoogleChromebrowser.
NativesupportfortheChromebrowserislogical,sinceNode.jsis
builtontopoftheGoogleV8JavaScriptEngine.Asweare
developingaserver-sideapplication,thesearenotthemost
convenienttools,asJsMockitoisnotpluggableasaNode.js
module,andusingadebuggerwithinyourbrowsertodebugbacked
applicationsjustdoesn'tseemrighttome.Anyway,ifyouareabout
todivedeeperintoNode.js,youshoulddefinitelygivethematry.
Fortestingserver-sideJavaScriptmodules,wewillusetheSinon.JSmodule.
Likealltheothermodules,itisavailableinthenpmrepository,soexecute
thefollowingcommandtoinstallit:
npminstall-gsinon
Sinon.JSisaveryflexibleJavaScripttestinglibraryproviding
functionalityformocking,stubbing,andspyingonJavaScript
objects.Itisavailableathttp://sinonjs.organdcanbeusedwithany
JavaScripttestingframework.Let'sseewhatweneedinorderto
testourHTTPmodule.Itexportsasinglemethod,handleRequest,
whichtakestheHTTPrequestandresponseobjectsasarguments.
Basedontherequestedmethod,themodulecallsitsinternal
functionstohandledifferentrequests.Eachrequesthandlerwrites